package org.jprogger.myworld.api.service;

import java.util.Map;

import org.jprogger.myworld.api.ApiServiceInvocationException;
import org.jprogger.myworld.api.app.AppContext;
import org.jprogger.myworld.api.http.ApiServiceHttpClient;
import org.jprogger.myworld.api.request.ApiRequest;
import org.jprogger.myworld.api.request.ApiRequestFactory;
import org.jprogger.myworld.api.response.ApiResponse;
import org.jprogger.myworld.api.response.AbstractApiResponseHandler;
import org.jprogger.myworld.api.secure.ApiRequestSigner;
import org.jprogger.myworld.api.secure.SignRequestException;

/**
 * 
 * @author jprogger
 *
 */
public class BaseApiService {

	protected AppContext context;
	
	public BaseApiService(AppContext context) {
		this.context = context;
	}
	
	/**
	 * 
	 * @param <T>
	 * @param params
	 * @param handler
	 * @return
	 */
	protected <T> ApiResponse<T> apiCall(Map<String, Object> params, AbstractApiResponseHandler<T> handler) 
			throws ApiServiceInvocationException{
		
		if (context != null && context.getAppParams() != null && context.getApiParams() != null)
		{
			ApiResponse<T> apiResponse = null;
			ApiServiceHttpClient apiClient = ApiServiceHttpClient.getInstance();
			params.put("secure", context.getApiParams().getIsRequestSecure());
			params.put("format", context.getApiParams().getFormat());
			params.put("app_id", context.getAppParams().getApplicationId());
			if (params.get("uid") == null)
			{
				params.put("session_key", context.getAppParams().getSessionKey());
			}
			ApiRequest apiRequest = 
				ApiRequestFactory.createApiRequest(context.getApiParams().getApiHost(), params);
			try 
			{
				apiRequest = ApiRequestSigner.signRequest(apiRequest, context.getApiParams().getSecretKey());
				String response = apiClient.sendRequest(apiRequest);
				apiResponse = handler.handleResponse(apiRequest, response);
			} 
			catch (SignRequestException e) 
			{
				throw new ApiServiceInvocationException("Unable to sign request!", e);
			}
			return apiResponse;
		}
		else 
		{
			throw new ApiServiceInvocationException("App Context not initialized!");
		}
	}
}
